package org.ix.dynamicapis.configure.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {

    private static final Logger logger= LoggerFactory.getLogger(JsonUtils.class);

    public static <T> String toJsonString(T t) {
        if (t == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            logger.error("对象转 json 失败", e);
        }
        return null;
    }

    public static <T> T parseObject(String json, Class<T> clazz)  {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 匹配不上的字段忽略

        try {
            return mapper.readValue(json, clazz);
        } catch (JsonMappingException e) {
            logger.error("json 转对象失败", e);
        } catch (JsonProcessingException e) {
            logger.error("json 转对象失败", e);
        }
        return null;
    }

    public static <T> List<T> parseList(String json, Class<T> clazz) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, clazz);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 匹配不上的字段忽略

        try {
            return (List<T>) mapper.readValue(json, javaType);
        } catch (JsonMappingException e) {
            logger.error("json 转对象失败", e);
        } catch (JsonProcessingException e) {
            logger.error("json 转对象失败", e);
        }
        return null;
    }

    public static <K, V> Map<K, V> parseMap(String json, Class<K> kClazz, Class<V> vClazz)   {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, kClazz, vClazz);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 匹配不上的字段忽略

        try {
            return (Map<K, V>) mapper.readValue(json, javaType);
        } catch (JsonMappingException e) {
            logger.error("json 转对象失败", e);
        } catch (JsonProcessingException e) {
            logger.error("json 转对象失败", e);
        }
        return null;
    }
}